#!/usr/bin/env python
#-*- coding: utf-8 -*-

######################################################################
# Copyright (c) 2010 Eugene Vorobkalo.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Public License v2.0
# which accompanies this distribution, and is available at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
#
# Contributors:
#       Eugene Vorobkalo - initial API and implementation
#       Andrey Fedorov - CSV
######################################################################

import os
from cfg import DEBUG_LEVEL
from pprint import pprint
import csv
import codecs
from zipfile import ZipFile
#import sys;

#reload(sys);
#sys.setdefaultencoding("utf8")

TEMP_PATH = os.path.join(os.path.dirname(__file__), '../db/CSV_Data')

CSV_CLIENT = 'Ref_Clients.csv'
CSV_CLIENT_GR = 'Ref_Clients_Groups.csv'
CSV_PRODUCT_GR = 'Ref_Products_Groups.csv'
CSV_PRODUCT = 'Ref_Products.csv'
CSV_PRICELISTS = 'Ref_PriceLists.csv'
CSV_PRICES = 'Ref_Products_Prices.csv'
CSV_FIRMS = 'Ref_Firms.csv'
CSV_TYPEDOC = 'Ref_DocTypes.csv'
CSV_DOCS = 'Docs_Data.csv'
CSV_LOCATION = 'location.csv'


Log = lambda str, err=False: pprint(str)

def init(CallBackLog):
    global Log
    Log = CallBackLog

def SetDocs(AgentID, DocsData):

    ZIP_FILE = os.path.join(os.path.dirname(__file__), '../db/CSV_Data/TEST_DOCS_%d.zip'%AgentID).replace('\\','/')
    z = ZipFile(ZIP_FILE, 'w')
    buf = '_id;device_guid;central_uid;pricelist_uid;firm_uid;client_uid;mainsumm;itemcount\r\n*order_id;product_uid;qty;price\r\n'
    for row in DocsData:
        if '_type_' in row:
            buf += '"%s";"%s";"%s";"%s";"%s";"%s";"%s";"%s"\r\n'%(row['_id'],row['device_guid'],row['central_uid'],row['pricelist_uid'],row['firm_uid'],row['client_uid'],row['mainsumm'],row['itemcount'])
        else:
            buf += '*"%s";"%s";"%s";"%s"\r\n'%(row['order_id'],row['product_uid'],row['qty'],row['price'])
    z.writestr('docdata.txt', buf)
    z.close()
    return True

def SetLocation(AgentID, location):
    return True

